from tinyops.library.json_helper import JsonHelper
from tinyops.config import Config


class Task:

    def __init__(self, name: str, config: Config, env: dict = None):
        self.name = name
        self.config = config
        self.env = env
        task_config = config.task(name)
        self.script = task_config.script
        self.script_file = task_config.script_file
        self.steps = task_config.steps
        self.notifier = task_config.notifier
        self.timeout = task_config.timeout

    def __repr__(self):
        return f'<{type(self).__name__} {self.name}>'

    @classmethod
    def from_config(cls, name: str, config: Config, env: dict = None):
        task = cls(name=name, config=config, env=env)
        return task

    def to_json(self) -> str:
        data = dict(name=self.name, env=self.env)
        return JsonHelper.dumps(data, indent=4)

    @classmethod
    def from_json(cls, text: str, config: Config):
        data = JsonHelper.loads(text)
        return cls(config=config, name=data['name'], env=data['env'])
